package edu.yuhf.dao.mysql;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.yuhf.dbutils.JdbcTemplate;
import com.yuhf.dbutils.ResultSetHandler;

import edu.yuhf.dao.convert.PermissionHandler;
import edu.yuhf.dao.iface.PermissionRoleDao;
import edu.yuhf.domain.Permission;
import lombok.extern.log4j.Log4j;

@Log4j
public class PermissionRoleJdbcDaoImpl implements PermissionRoleDao{

	@Override
	public int insertData(int roleId, String[] permissionIds) {
		int rowNumber=0;
		int count=0;
		StringBuilder sb=new StringBuilder("insert into umm_permission_role(role_id,permission_id) values");
		if(permissionIds.length!=0) {
			for(String permissionId:permissionIds) {
				if(count==0) {
					sb.append("(").append(roleId).append(",").append(permissionId).append(")");					
				}else {
					sb.append(",(").append(roleId).append(",").append(permissionId).append(")");	
				}
				count++;
			}		
			rowNumber=JdbcTemplate.update(sb.toString());
		}
		return rowNumber;
	}

	@Override
	public int deleteData(int roleId) {
		int rowNumber=0;
		String sql="delete from umm_permission_role where role_id=?";
		rowNumber=JdbcTemplate.update(sql, roleId);
		return rowNumber;
	}

	@Override
	public List<Permission> queryPermissionsByRoleId(int roleId) {
		String sql="select p.id from umm_permission p inner join umm_permission_role pr on p.id=pr.permission_id where pr.role_id=?";
		List<Permission> list=JdbcTemplate.query(sql,rs->{
			List<Permission> list0=new ArrayList<>();
			try {
				while(rs.next()) {
					Permission p=new Permission(rs.getInt(1),0,"","","");
					list0.add(p);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			return list0;
		}, roleId);
		return list;
	}

}
